Generating random numbers

Problem

You want to generate random numbers.

Solution

For uniformly distributed (flat) random numbers, use runif(). By default, its range is from 0 to 1.

runif(1)
# 0.5581546

# Get a vector of 4 numbers
runif(4)
# 0.383330465 0.005814167 0.879704937 0.873534007

# Get a vector of 3 numbers from 0 to 100
runif(3, min=0, max=100)
# 78.09879 85.37001 15.13357

# Get 3 integers from 0 to 100
# Use max=101 because it will never actually equal 101
floor(runif(3, min=0, max=101))
# 40 59 64
# This will do the same thing
sample(1:100, 3, replace=T)

# To generate integers WITHOUT replacement:
sample(1:100, 3, replace=F)

To generate numbers from a normal distribution, use rnorm(). By default the mean is 0 and the standard deviation is 1.

rnorm(4)
#  1.04043144 -1.02006411  1.97268110  0.02424849

# Use a different mean and standard deviation
rnorm(4, mean=50, sd=10)
# 30.29251 48.75306 51.08491 50.04595

# To check that the distribution looks right, make a histogram of the numbers
x <- rnorm(400, mean=50, sd=10)
hist(x)

Notes

If you want to your sequences of random numbers to be repeatable, see ../Generating repeatable sequences of random numbers.